<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/4/12
 * Time: 17:46
 */

namespace app\model\production;




use app\model\BaseModel;

class ProductionModel extends BaseModel
{
    protected $table = 'ting_production';

    protected $primaryKey = 'productionid';

    const CREATED_AT = 'createtime';
    const UPDATED_AT = 'updatetime';

    protected static $instance;

    public static function getInstance()
    {
        if(is_object(self::$instance)){
            return self::$instance;
        }

        self::$instance = new self();

        return self::$instance;
    }

    public function attrs()
    {
        return $this->hasMany(ProductionAttrModel::class,'productionid','productionid')->where(['isdel'=>0])->orderBy('sort','asc');
    }

    public function index($where, $field=[],$order = [])
    {
        $query =  $this->getWhere($where);

        $field && $query->select($field);

        $data = $this->buildPage($query);

        $order && $query->orderBy($order[0],$order[1]);

        $data['data'] = $query->get();

        return $data;
    }

    public function getList($param)
    {
        $where = [
            'isdel'=>0,
            'status'=>1
        ];

        $query = $this->where($where);
        $data['data'] = $query->orderBy('createtime','desc')->get();

        return $data;
    }

    public function getDetail($where,$field=[])
    {
        $query = $this->getWhere($where);
        $field && $detail = $query->select($field);
        $detail =  $query->first();

        if($detail==false){
            throw new UserException(4020,'商品不存在');
        }

        return $detail;
    }

    public function insertData($param)
    {
        try{
            DB::beginTransaction();

            $maxId =  $this->where([['production_sn','>',0]])->max('production_sn');
            $data['production_sn'] = Common::getSnCode($maxId,'20',4);
            $url = config('app.url').'/index/production/index/getdetail?production_sn='.$data['production_sn'];
            $qrcode = QRCodeImage::getInstance()->generateQrCode($url);
            $data['qrcode'] = $qrcode;

            $data['title'] = $param['title']??'';
            $data['subtitle'] = $param['subtitle']??'';
            $data['sale_price'] = $param['sale_price']??0;
            $data['origin_price'] = $param['origin_price']??0;
            $data['main_image'] = $param['main_image'];
            $data['images'] = $param['images'] ? json_encode($param['images'],256):'[]';
            $data['desc_content'] = $param['desc_content'] ? json_encode($param['desc_content'],256) : '[]';
            $data['status'] = 1;
            $data['createtime'] = date('Y-m-d H:i:s');
            $data['updatetime'] = date('Y-m-d H:i:s');
            $data['adduser'] = request()->curUserId;

            $id = $this->insertGetId($data);

            if(!empty($param['attr_config'])){
                $attrData = [];
                foreach($param['attr_config'] as $val){
                    $attrData[] = [
                        'name'=>$val['name'],
                        'unit'=>$val['unit'],
                        'sale_price'=>$val['sale_price'],
                        'origin_price'=>$val['origin_price'],
                        'sort'=>$val['sort'],
                        'status'=>$val['status']??1,
                        'productionid'=>$id,
                        'createtime'=> date('Y-m-d H:i:s'),
                        'updatetime'=> date('Y-m-d H:i:s'),
                        'adduser'=>  request()->curUserId,
                    ];
                }
                $attrData && ProductionAttrModel::getInstance()->insert($attrData);
            }
            DB::commit();

            return $id;
        }catch (UserException $e){
            DB::rollBack();
            throw $e;
        }
    }

    public function updateData($param)
    {
        $info = $this->find($param['productionid']);
        if($info==false){
            throw new UserException(4040);
        }

        try{
            DB::beginTransaction();
            $data = [];
            !empty($param['title']) && $data['title'] = $param['title'];
            !empty($param['subtitle']) && $data['subtitle'] = $param['subtitle'];
            !empty($param['sale_price']) && $data['sale_price'] = $param['sale_price'];
            !empty($param['origin_price']) && $data['origin_price'] = $param['origin_price'];
            !empty($param['main_image']) && $data['main_image'] = $param['main_image'];
            isset($param['images']) && ($data['images'] = $param['images'] ? json_encode($param['images'],256):'[]');
            isset($param['desc_content']) && ($data['desc_content'] = $param['desc_content'] ? json_encode($param['desc_content'],256) : '[]');
            isset($param['sort']) && $data['sort'] = $param['sort'];
            !empty($param['isdel']) && $data['isdel'] = $param['isdel'];
            if(isset($param['status'])){
                $data['status'] = $param['status']==1 || strtolower($param['status'])=='on'? 1 : 0;
            }
            $data['updatetime'] = date('Y-m-d H:i:s');

            if($info['qrcode']==false){
                $url = config('app.url').'/index/production/index/getdetail?production_sn='.$info['production_sn'];
                $qrcode = QRCodeImage::getInstance()->generateQrCode($url);
                $data['qrcode'] = $qrcode;
            }
            $result = $this->where(['productionid'=>$param['productionid']])->update($data);

            $attrData = [];
            foreach($param['attr_config'] as $val){
                $attrData[] = [
                    'name'=>$val['name'],
                    'unit'=>$val['unit'],
                    'sale_price'=>$val['sale_price'],
                    'origin_price'=>$val['origin_price'],
                    'sort'=>$val['sort'],
                    'status'=>$val['status']??1,
                    'productionid'=>$param['productionid'],
                    'createtime'=> date('Y-m-d H:i:s'),
                    'updatetime'=> date('Y-m-d H:i:s'),
                    'adduser'=>  request()->curUserId,
                ];
            }
            if($attrData){
                ProductionAttrModel::getInstance()->getWhere(['productionid'=>$param['productionid']])->delete();
                ProductionAttrModel::getInstance()->insert($attrData);
            }

            DB::commit();
            return $result;

        }catch (UserException $e){
            DB::rollBack();
            throw $e;
        }
    }

    public function saveData($param)
    {
        if($param['productionid']>0){

            return $this->updateData($param);
        }else{
            return $this->insertData($param);
        }
    }

    public function deleteData($param)
    {
        $detail = $this->find($param['productionid']);
        if($detail==false){
            throw new UserException(4040);
        }

        if($detail['status']==1){
            throw new UserException(4020,'下架才能删除');
        }

        $update = [
            'isdel'=>1,
            'updatetime'=>date('Y-m-d H:i:s')
        ];

        $result = $this->where(['productionid'=>$param['productionid']])->update($update);

        return $result;
    }
}